package com.schoolCommunity.controller;


import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.schoolCommunity.util.GetIpAddress;
import lombok.AllArgsConstructor;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import com.schoolCommunity.entity.Information;
import com.schoolCommunity.entity.Member;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author YTH
 * @since 2020-09-06
 */
@CrossOrigin
@RestController
public class MemberController {

    @Autowired
    private com.schoolCommunity.service.MemberService MemberService;
    @Autowired
    private Producer captchaProducer = null;
    @Autowired
    @Qualifier("MyLoginTemplate")
    private RedisTemplate redisTemplate;
    @Autowired
    private GetIpAddress getIpAddress;

    Logger log = Logger.getLogger(MemberController.class);


    //返回注册验证码给前端
    @RequestMapping("/kaptcha")
    public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        //生成验证码
        String capText = captchaProducer.createText();
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);

        //获取客户端ip
        String ipAddress = getIpAddress.getIpAddress(request);
        //不知道客户端地址有时候获取错误
//        log.info("获取到的客户端IP是"+ipAddress);
        log.info("生成的验证码是" + capText);
        //因为这里ip地址有时候获取错误，测试使用硬编码
//        log.info("即将存入的redis验证码的key是"+ipAddress+Constants.KAPTCHA_SESSION_KEY);

        log.info("即将存入的redis验证码的key是:ipAddress+Constants.KAPTCHA_SESSION_KEY");
        redisTemplate.opsForValue().set("ipAddress+Constants.KAPTCHA_SESSION_KEY", capText, 30, TimeUnit.MINUTES);


        //向客户端写出
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }

    //返回密码验证码给前端
    @RequestMapping("/PassKaptcha")
    public void getPassKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        //生成验证码
        String capText = captchaProducer.createText();
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);

        //获取客户端ip
        String ipAddress = getIpAddress.getIpAddress(request);
        //不知道客户端地址有时候获取错误
//        log.info("获取到的客户端IP是"+ipAddress);
        log.info("生成的验证码是" + capText);
        //因为这里ip地址有时候获取错误，测试使用硬编码
//        log.info("即将存入的redis验证码的key是"+ipAddress+Constants.KAPTCHA_SESSION_KEY);

        log.info("即将存入的redis验证码的key是:ipAddress+Constants.KAPTCHA_SESSION_KEY");
        redisTemplate.opsForValue().set("PassKaptcha", capText, 30, TimeUnit.MINUTES);


        //向客户端写出
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }


    //测试接口，完成可以删除
    //使用Vue获取验证验证码正确性，并处理
    @GetMapping("/getKap/{mykap}/{email}")
    public String getKap(@PathVariable("mykap") String mykap, @PathVariable("email") String email, HttpServletRequest request) {
        log.info("获取到的vue验证码是" + email);
        log.info("获取到的邮箱是是" + mykap);
        String verifyCodeExpected = (String) request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
        log.info("后台生成的验证码是" + verifyCodeExpected);

        if (mykap == null || !mykap.equals(verifyCodeExpected)) {
            log.info("验证码不一致");
            return "验证码有误！";
        } else {
            log.info("验证码一致");
            return "hello,world";
        }

    }


    //单独校验邮箱验证码
    @GetMapping("checkEmailSignIn/{email}/{EmailSignIn}")
    public Information checkEmailSignIn(@PathVariable("email") String email,
                                        @PathVariable("EmailSignIn") String EmailSignIn) {

        return MemberService.checkEmailSignIn(email, EmailSignIn);
    }


    //注册，添加到member表
    @PostMapping("/InsertMember")
    public Information<Member> InsertMember(@RequestBody Member Member) {
        //仿数据
        //获取对象
//        Member Member1 = new Member();
//        Member1.setCollege("计算机学院")
//                .setEmail("1141649562@qq.com")
//                .setFamilyName("张")
//                .setGrade(2017)
//                .setNickname("张三的昵称")
//                .setPassword("111111")
//                .setSex(0);
//        //对象传入的验证码
//        EmailSignIn = "7182";

        return MemberService.InsertMember(Member);

    }

    //登录
    @PostMapping("/LoginMember")
    public Information<Member> LoginMember(@RequestBody Member Member) {

        return MemberService.LoginMember(Member);

    }

    //获取注册邮箱验证码
    //参数为邮箱号码与图形验证码
    @PostMapping("/getSignInEmail/{email}/{kaptcha}")
    public Information getPassEmail(@PathVariable("email") String email,
                                    @PathVariable("kaptcha") String kaptcha,
                                    HttpServletRequest request) {

        return MemberService.SendSignInEmail(email, kaptcha, request);

    }

    //发送找回密码邮箱验证码
    @PostMapping("/getPassBackEmail/{email}/{kaptcha}")
    public Information getPassBackEmail(@PathVariable("email") String email,
                                        @PathVariable("kaptcha") String kaptcha,
                                        HttpServletRequest request) {

        return MemberService.SendGetPassEmail(email, kaptcha, request);

    }

    //校验找回密码的邮箱验证码，直接修改密码
    @PostMapping("/changePass/{EmailGetPass}")
    public Information checkAndChangePass(@PathVariable("EmailGetPass") String EmailGetPass, @RequestBody Member Member) {
        return MemberService.checkAndChangePass(Member, EmailGetPass);
    }

    //写入一张图片
    @PostMapping("/UploadPicture/{memberId}")
    public Information UploadPicture(@RequestParam("file") MultipartFile file, @PathVariable("memberId") long memberId) {
        return MemberService.UploadPicture(file, memberId);
    }

    //删除指定用户的一张图片
    @GetMapping("/DeletePicture/{memberId}")
    public Information DeletePicture(@PathVariable("memberId") long memberId) {
        return MemberService.DeletePicture(memberId);
    }

    //管理员功能，根据ID删除用户
    @GetMapping("/DeleteMember/{memberId}")
    public Information DeleteMember(@PathVariable("memberId") long memberId) throws IOException {
        return MemberService.DeleteMember(memberId);
    }

    //管理员功能，修改用户信用等级
    @GetMapping("/UpdateMemberCredit/{memberId}/{creditNumber}")
    public Information UpdateMemberCredit(@PathVariable("memberId") long memberId, @PathVariable("creditNumber") int creditNumber) {
        return MemberService.UpdateMemberCredit(memberId, creditNumber);
    }

    //管理员功能，获取所有用户
    @GetMapping("/GetAllMember")
    public Information GetAllMember() {
        return MemberService.GetAllMember();
    }


}

